package com.yonyou.hxjy.utils;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * @description: 幂等工具类
 * @author: nishch
 * @create: 2021-05-13
 **/
@Slf4j
public class ReSubmitUtil {

    //MDD幂等性传参
    private final static String RESUbMIT_CHECK_KEY = "resubmitCheckKey";
    //配置可能存在的基础路径
    private final static String BASE_DATA = "data";
    //接口请求类型强制校验参数
    private final static String STATUS_INSERT = "insert";
    //接口状态参数
    private final static String STATUS = "_status";

    public static <T>T resubmitCheckKey(T t){
        try {
            String resubmitCheckKeyV = md5Encode(t);
            Object reqData = getRealData(t);
            BeanUtils.setProperty(reqData,RESUbMIT_CHECK_KEY, resubmitCheckKeyV);
        }catch (Exception e){
            log.info("幂等参数添加异常:"+ JSON.toJSON(t).toString());
        }
        return t;
    }

    private static Object getRealData(Object object) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        String isData = BeanUtils.getProperty(object,BASE_DATA);
        if(!StringUtils.isEmpty(isData)){
            object = PropertyUtils.getProperty(object,BASE_DATA);
        }
        return object;
    }

    public static String md5Encode(Object object){
        byte[] bytes = JSON.toJSONBytes(object);
        return DigestUtils.md5DigestAsHex(bytes);
    }

    /**
     * 暂不做校验
     * @param object
     * @throws Exception
     */
//    private static void checkInfType(Object object) throws Exception {
//        String isHasData = BeanUtils.getProperty(object,STATUS);
//        if(StringUtils.isEmpty(isHasData)||!STATUS_INSERT.equals(StringUtils.trim(isHasData).toLowerCase())){
//            throw new Exception("请确定是保存接口，且放在data值里");
//        }
//    }

}
